package org.pathlet.util;

import org.pathlet.core.InstanceSpace;
import org.pathlet.core.Path;
import org.pathlet.core.PathletResource;

public class PathletUtils {

	/**
	 * Get the resource by the path string.
	 * @param pathStr the path string
	 * @param currentWorkingResource 当前工作的资源（相对路径的基准），如果pathStr是绝对路径，则此参数无效
	 * @param currentWorkingSpace 当前工作的空间
	 * @return
	 */
	public static PathletResource getResource(String pathStr, PathletResource currentWorkingResource, InstanceSpace currentWorkingSpace) {

		Path resPropPath = new Path(pathStr);
		if(resPropPath.isAbsolute() == false) {
			//Convert propPath to absolute path:  Target ResoucePath + propPath = absolute path
			resPropPath = new Path(currentWorkingResource.getPath().getParent(), pathStr);
		}

		return currentWorkingSpace.getContainer().getResource(resPropPath);
	}

	public static Object getInstance(String pathStr, PathletResource currentWorkingResource, InstanceSpace currentWorkingSpace) {
		Path propPath = new Path(pathStr);
		if(propPath.isAbsolute() == false) {
			//Convert propPath to absolute path:  Target ResoucePath + propPath = absolute path
			propPath = new Path(currentWorkingResource.getPath().getParent(), pathStr);
		}

		return currentWorkingSpace.getInstance(propPath, false, false);
	}

	public static Object getInstanceByType(String typeClassName, InstanceSpace space) {
		return space.getInstanceByType(typeClassName);
		//Object ret = space.getInstance(new Path("/system/SysConfigMapper"), false, false);
		//System.out.println("InstanceByType instance type: " + ret.getClass().getName());
		//return ret;
	}

	public static InstanceSpace getSpace(String designatedScope, InstanceSpace currentWorkingSpace) {

		InstanceSpace spaceValue = currentWorkingSpace;
		boolean foundContext = false;
		while(spaceValue != null) {
			if(designatedScope.equals(spaceValue.getScope())) {
				foundContext = true;
				break;
			}
			spaceValue = spaceValue.getParent();
		}

		if(foundContext == true) {
			return spaceValue;
		}
		else {
			return null;
		}
	}
}
